{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e22fcce0ee4a12fa",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# Connect to Label Studio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:44.791239Z",
     "start_time": "2024-08-13T11:45:44.781498Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from label_studio_sdk import LabelStudio\n",
    "\n",
    "ls = LabelStudio(\n",
    "    base_url=os.getenv('LABEL_STUDIO_URL', 'http://localhost:8080'),\n",
    "    api_key=os.getenv('LABEL_STUDIO_API_KEY'),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39e40e7b1120c335",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# Create New Project\n",
    "\n",
    "First we need to define a **Labeling Interface** for the new project:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "93e728713446e20f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:44.814719Z",
     "start_time": "2024-08-13T11:45:44.809849Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<View>\n",
      "  <Text name=\"text\" value=\"$text\"/>\n",
      "  <Choices name=\"label\" toName=\"text\">\n",
      "    <Choice value=\"Positive\"/>\n",
      "    <Choice value=\"Negative\"/>\n",
      "  </Choices>\n",
      "</View>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from label_studio_sdk.label_interface import LabelInterface\n",
    "from label_studio_sdk.label_interface.create import choices\n",
    "\n",
    "label_config = LabelInterface.create({\n",
    "    'text': 'Text',\n",
    "    'label': choices(['Positive', 'Negative'])\n",
    "})\n",
    "print(label_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79099883515b82c2",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "You can manually create [XML configuration for the labeling interface](https://labelstud.io/tags), but `LabelInterface` class provides a convenient way to create it programmatically.\n",
    "\n",
    "Now let's create a new project with the specified labeling interface:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7f05d9e5f6d25125",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:44.872356Z",
     "start_time": "2024-08-13T11:45:44.816740Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created project:\n",
      "http://localhost:8080/projects/7\n"
     ]
    }
   ],
   "source": [
    "project = ls.projects.create(\n",
    "    title='Text Classification',\n",
    "    label_config=label_config\n",
    ")\n",
    "\n",
    "print(f'Created project:\\n{ls._client_wrapper.get_base_url()}/projects/{project.id}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a106abb6cb3c42a1",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# Import Tasks to the Project"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f4d556fb04165434",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:44.975709Z",
     "start_time": "2024-08-13T11:45:44.874324Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ProjectsImportTasksResponse(annotation_count=None, could_be_tasks_list=None, data_columns=None, duration=None, file_upload_ids=None, found_formats=None, predictions_count=None, task_count=None, import=434811)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ls.projects.import_tasks(\n",
    "    id=project.id,\n",
    "    request=[\n",
    "        {\"text\": \"Hello world\"},\n",
    "        {\"text\": \"Hello Label Studio\"},\n",
    "        {\"text\": \"What a beautiful day\"},\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "792066fed100cbda",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Import Tasks with Pre-annotations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5df9f60ae30651f8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:45.075813Z",
     "start_time": "2024-08-13T11:45:44.977719Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ProjectsImportTasksResponse(annotation_count=None, could_be_tasks_list=None, data_columns=None, duration=None, file_upload_ids=None, found_formats=None, predictions_count=None, task_count=None, import=434814)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ls.projects.import_tasks(\n",
    "    id=project.id,\n",
    "    request=[\n",
    "        {\"text\": \"Hello world\", \"sentiment\": \"Positive\"},\n",
    "        {\"text\": \"Goodbye Label Studio\", \"sentiment\": \"Negative\"},\n",
    "        {\"text\": \"What a beautiful day\", \"sentiment\": \"Positive\"},\n",
    "    ],\n",
    "    preannotated_from_fields=['sentiment']\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47dd92fcdab936f8",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "More customizable way to import preannotations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "687a17f9e370f275",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:45.818898Z",
     "start_time": "2024-08-13T11:45:45.077904Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from label_studio_sdk.label_interface.objects import PredictionValue\n",
    "\n",
    "# this returns the same `LabelInterface` object as above\n",
    "li = ls.projects.get(id=project.id).get_label_interface()\n",
    "\n",
    "# by specifying what fields to `include` we can speed up task loading\n",
    "for task in ls.tasks.list(project=project.id, include=[\"id\"]):\n",
    "    task_id = task.id\n",
    "    prediction = PredictionValue(\n",
    "        # tag predictions with specific model version string\n",
    "        # it can help managing multiple models in Label Studio UI\n",
    "        model_version='my_model_v1',\n",
    "        # define your labels here\n",
    "        result=[\n",
    "            li.get_control('label').label(['Positive']),\n",
    "        ]\n",
    "    )\n",
    "    ls.predictions.create(task=task_id, **prediction.model_dump())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58cde0e2e4659c0f",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# Export Annotations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "24e1333f469965b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-13T11:45:46.003612Z",
     "start_time": "2024-08-13T11:45:45.821692Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9079561\n",
      "[]\n",
      "[LseTaskPredictionsItem(created_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 306773, tzinfo=datetime.timezone.utc), model=None, model_run=None, model_version='my_model_v1', project=462621, result=[{'id': '787be9ad-a2a7-411a-b567-ceeb84a5923a', 'type': 'choices', 'value': {'choices': ['Positive']}, 'to_name': 'text', 'from_name': 'label'}], score=0.0, task=9079561, updated_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 306787, tzinfo=datetime.timezone.utc), id=3584252, created_ago='0\\xa0minutes', cluster=None, neighbors=None, mislabeling=0.0)]\n",
      "9079562\n",
      "[]\n",
      "[LseTaskPredictionsItem(created_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 613908, tzinfo=datetime.timezone.utc), model=None, model_run=None, model_version='my_model_v1', project=462621, result=[{'id': '19f8fc4b-d2be-4700-9b8b-c172d130215b', 'type': 'choices', 'value': {'choices': ['Positive']}, 'to_name': 'text', 'from_name': 'label'}], score=0.0, task=9079562, updated_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 613919, tzinfo=datetime.timezone.utc), id=3584253, created_ago='0\\xa0minutes', cluster=None, neighbors=None, mislabeling=0.0)]\n",
      "9079563\n",
      "[]\n",
      "[LseTaskPredictionsItem(created_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 815603, tzinfo=datetime.timezone.utc), model=None, model_run=None, model_version='my_model_v1', project=462621, result=[{'id': '1596282f-2c3b-4fef-83b0-2a0680686bbe', 'type': 'choices', 'value': {'choices': ['Positive']}, 'to_name': 'text', 'from_name': 'label'}], score=0.0, task=9079563, updated_at=datetime.datetime(2025, 10, 1, 21, 0, 54, 815615, tzinfo=datetime.timezone.utc), id=3584254, created_ago='0\\xa0minutes', cluster=None, neighbors=None, mislabeling=0.0)]\n"
     ]
    }
   ],
   "source": [
    "for task in ls.tasks.list(project=project.id):\n",
    "    print(task.id)\n",
    "    print(task.annotations)\n",
    "    print(task.predictions)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0c80cf5bbc3ffc0",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "Read more about task, annotations and predictions format in Label Studio [documentation](https://labelstud.io/guide/export#Label-Studio-JSON-format-of-annotated-tasks)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
